package com.megaspacevr.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Configuration
public class ImageOptimizationConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加静态资源处理，启用缓存
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(7200); // 2小时缓存
        
        registry.addResourceHandler("/images/**")
                .addResourceLocations("classpath:/images/")
                .setCachePeriod(86400); // 24小时缓存
    }

    /**
     * 图片压缩工具
     */
    public static class ImageCompressor {
        
        /**
         * 压缩图片到指定大小
         * @param originalFile 原始文件
         * @param targetFile 目标文件
         * @param maxWidth 最大宽度
         * @param maxHeight 最大高度
         * @param quality 质量(0.0-1.0)
         */
        public static void compressImage(File originalFile, File targetFile, 
                                       int maxWidth, int maxHeight, float quality) throws IOException {
            BufferedImage originalImage = ImageIO.read(originalFile);
            
            // 计算缩放比例
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            
            double scaleX = (double) maxWidth / originalWidth;
            double scaleY = (double) maxHeight / originalHeight;
            double scale = Math.min(scaleX, scaleY);
            
            int newWidth = (int) (originalWidth * scale);
            int newHeight = (int) (originalHeight * scale);
            
            // 创建缩放后的图片
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = resizedImage.createGraphics();
            
            // 设置高质量渲染
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();
            
            // 保存压缩后的图片
            ImageIO.write(resizedImage, "jpg", targetFile);
        }
        
        /**
         * 生成WebP格式图片（如果需要）
         */
        public static void generateWebP(File jpegFile, File webpFile) {
            // 这里可以集成WebP转换库，如imageio-webp
            // 暂时留作扩展接口
        }
    }
} 